package demo.thread;

import java.util.Date;

/**
 * 线程分为前台线程和后台线程(也叫守护线程、精灵线程、俗称Daemon线程)
 * 区别：Java默认创建的子线程都是前台线程，当所有前台线程执行完毕时，程序会正常终止，此时所有的后台线程也会被终止（即使它还没执行完毕）
 * 可调用thread.setDaemon(true);把某个线程设为后台线程
 * @author Administrator
 *
 */
public class DameonDemo {
	
	public static void main(String[] args) throws Exception {
		Runnable r = new Runnable() {
			public void run() {
				String daemon = (Thread.currentThread().isDaemon() ? "我是后台线程" : "不是后台线程");
				while (true) {
					System.out.println("我正在运行" + Thread.currentThread().getName() + "-" + new Date());
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						System.out.println("I was interrupt, I am " + daemon);
					}
				}
			}

		};
		
		
		Thread t = new Thread(r);
		//t.setDaemon(true);//该行如果注释掉，对比下结果
		t.start();
		Thread.sleep(3000);
		System.out.println("主线程还活着吗？"+Thread.currentThread().isAlive());
		
		/*new MyThread().start();
		
		System.out.println("主线程还活着吗？"+Thread.currentThread().isAlive());*/
	}
}

class MyThread extends Thread{
	public void run() {
		for (int i = 0; i < 5; i++) {
			System.out.println( Thread.currentThread().getName() + "第二个子线程正在运行" + i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
}